package com.fulihui.wgj.biz.impl;

import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.util.Base64Utils;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.weixinsdk.result.user.UserInfoGetResult;
import com.fulihui.wgj.biz.SendHistoryUserBiz;
import com.fulihui.wgj.biz.WeiXinSdkBiz;
import com.fulihui.wgj.dal.impala.domain.WxUserInfo;
import com.fulihui.wgj.dal.mybatis.domain.WxHistorySendUser;
import com.fulihui.wgj.dal.mybatis.repository.WxHistorySendUserRepository;
import com.fulihui.wgj.facade.request.wxuser.WxHistorySendUserSaveRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author: Levon
 * @date: 2018-07-26 14:47
 */
@Service
public class SendHistoryUserBizImpl implements SendHistoryUserBiz {

    @Autowired
    private WxHistorySendUserRepository wxHistorySendUserRepository;

    @Autowired
    private WeiXinSdkBiz weiXinSdkBiz;

    @Override
    public void saveHistorySendUser(WxHistorySendUserSaveRequest request) {
        ConditionValidator.validate(request);
        WxHistorySendUser sendUserQuery = new WxHistorySendUser();
        sendUserQuery.setOpenid(request.getOpenid());
        WxHistorySendUser exist = wxHistorySendUserRepository.queryOne(sendUserQuery);
        if (Objects.isNull(exist)) {
            //从微信获取用户详细信息，保存到历史发送记录表
            UserInfoGetResult userDetail = weiXinSdkBiz.getUserDetail(request.getAppId(), request.getOpenid());
            if (userDetail.isSuccess()) {
                WxUserInfo wxUserInfo = weiXinSdkBiz.weiXinModel2DbModel(userDetail);
                if (Objects.nonNull(wxUserInfo)) {
                    WxHistorySendUser sendUser = BeanConv.copy(wxUserInfo, WxHistorySendUser.class);
                    // 微信昵称有emoji表情时 mysql无法存储
                    sendUser.setNickname(Base64Utils.encode(wxUserInfo.getNickname()));
                    sendUser.setAppId(request.getAppId());
                    wxHistorySendUserRepository.saveSelective(sendUser);
                }
            }
        }
    }
}
